package com.per.hjh.intercetor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.per.other.until.DateTimeUtil;
import com.per.other.until.UserHelper;

public class LoginInterceptor extends HandlerInterceptorAdapter implements InitializingBean {
	static Log log = LogFactory.getLog(LoginInterceptor.class);
	
	//系统启动并初始化一次的变量
	private Map<String,Object> globalRenderVariables = new HashMap<String,Object>();
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		System.err.println("----------");
		return super.preHandle(request, response, handler);
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
	
		if(modelAndView == null) {
		
			return;
		}
		
        String viewName = modelAndView.getViewName();
        modelAndView.addAllObjects(globalRenderVariables);
        modelAndView.addAllObjects(perRequest(request,response));
        if(viewName != null && !viewName.startsWith("redirect:")) {
            
        }
	}
	protected Map<String,Object> perRequest(HttpServletRequest request,HttpServletResponse response) {
		HashMap<String,Object> model = new HashMap<String,Object>();
		HttpSession session = request.getSession();
		String fullPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
		
		model.put("current_time", DateTimeUtil.getTimeStamp(new Date(), "yyyy-MM-dd HH:mm"));
		model.put("current_date", DateTimeUtil.getTimeStamp(new Date(), "yyyy-MM-dd"));
		model.put("loginUser", UserHelper.getLoginUser(request));
		model.put("ctx", fullPath);
		System.err.println(fullPath);
		return model;
	}
	//用于初始化 sharedRenderVariables, 全局共享变量请尽量用global前缀
		private void initSharedRenderVariables() {
			globalRenderVariables.put("global_system_start_time", new Date());
			globalRenderVariables.put("url_prefix", "http://");
			globalRenderVariables.put("img_url_prefix", "http://");
			globalRenderVariables.put("static_url_prefix", "http://");
			
			//也可以存放一些共享的工具类,以便视图使用,如StringUtils
			
		}
		
		//在系统启动时会执行
		public void afterPropertiesSet() throws Exception {
			System.out.println("ceshi init-method");
			initSharedRenderVariables();
		}


	
}
